package com.cl.rabbitmqstart.rabbit;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@RestController
public class SendMessageController {

    private final RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法
    private final MyService myService;  //Bean注入

    public SendMessageController(RabbitTemplate rabbitTemplate, MyService myService) {
        this.rabbitTemplate = rabbitTemplate;
        this.myService = myService;
    }


    @GetMapping("/testMyService")
    public String testMyService() {
        return myService.print();
    }

    @GetMapping("/sendDirectMessage")
    public Map<String, Object> sendDirectMessage() {
        String messageData = "test message, hello!";
        Map<String, Object> map = mapCreate(messageData);
        //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", map);
        return map;
    }

    @GetMapping("/sendTopicMessage1")
    public Map<String, Object> sendTopicMessage1() {
        String messageData = "message: M A N ";
        Map<String, Object> map = mapCreate(messageData);
        rabbitTemplate.convertAndSend("topicExchange", TopicRabbitConfig.man, map);
        return map;
    }

    @GetMapping("/sendTopicMessage2")
    public Map<String, Object> sendTopicMessage2() {
        String messageData = "message: woman is all ";
        Map<String, Object> map = mapCreate(messageData);
        rabbitTemplate.convertAndSend("topicExchange", TopicRabbitConfig.woman, map);
        return map;
    }

    @GetMapping("/sendFanoutMessage")
    public Map<String, Object> sendFanoutMessage() {
        String messageData = "message: testFanoutMessage ";
        Map<String, Object> map = mapCreate(messageData);
        rabbitTemplate.convertAndSend("fanoutExchange", "", map);
        return map;
    }

    @GetMapping("/TestMessageAck2")
    public String TestMessageAck2() {
        String messageData = "message: lonelyDirectExchange test message ";
        Map<String, Object> map = mapCreate(messageData);
        rabbitTemplate.convertAndSend("lonelyDirectExchange", "TestDirectRouting", map);
        return "ok";
    }

    private Map<String, Object> mapCreate(String messageData) {
        String messageId = String.valueOf(UUID.randomUUID());
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> map = new HashMap<>();
        map.put("messageId", messageId);
        map.put("messageData", messageData);
        map.put("createTime", createTime);
        return map;
    }
}